/*
 * MixerMission.h
 *
 *  Created on: Nov 27, 2013
 *      Author: wyf
 *    Modified: Mar 12, 2015
 *    Modifier: Dellinger.Zhang
 */

#ifndef MIXERMISSION_H_
#define MIXERMISSION_H_

#include <sys/time.h>
#include <list>
#include <map>
#include "ctType.h"
#include "ctSocket.h"
#include "AudioCommand.h"
#include "ct_udp_socket.h"

#include "webrtc/common_types.h"
#include "webrtc/voe_base.h"
#include "webrtc/voe_mixer.h"
#include "webrtc/voe_codec.h"
#include "webrtc/voe_network.h"
#include "webrtc/voe_rtp_rtcp.h"
#include "webrtc/voe_external_media.h"
#include "webrtc/voe_audio_processing.h"

#include "PacketQueue.h"
//#include "ThreadDecoding.h"

using namespace webrtc;

class MixerMission : public Streamout, public Transport {
public:
	static DWORD Create(MixerMission*& mission, DWORD roomid, DWORD recid, DWORD sttime, DWORD endtime, const char *path);
	static void Destroy(MixerMission*& mixer);

	virtual ~MixerMission();
	void init();
    DWORD getRoomId()
    {
        return _MissionID;
    }
    DWORD getRecId()
    {
        return recid_;
    }
    
	void updateMissionTime(DWORD sttime, DWORD endtime);
    bool isTimeOut(DWORD curtime);

	void clear();
	bool process();

public:
	//handle
	void start();
	void stop();
	void handlePacket(uint8_t* buf, DWORD len);
public:
	//put into queue
	void onRtpPacket(UDPPacket* pack);
	void onRtcpPacket(UDPPacket* pack);

    void getAudioPacket(t_BufferCmdQueue &to);
    virtual int onRawPcm(const void *data, int len, int samples_per_sec, int num_channels);
	virtual int SendPacket(int channel, const void *data, int len);
	virtual int SendRTCPPacket(int channel, const void *data, int len) {
		return 0;
	}
    void addMute(const uint8_t *data, const uint32_t &datalen);

private:
	void addChannel();
	void delChannel();

private:
	MixerMission(DWORD roomid, DWORD recid, DWORD sttime, DWORD endtime, const char *path);
    bool createFileName(const DWORD &recid, std::string &filename);

private:
	typedef std::map<DWORD, DWORD> channelMap;
	typedef channelMap::iterator TM_IT;
	typedef channelMap::const_iterator TM_CIT;
	typedef channelMap::value_type TM_VT;

	DWORD _MissionID;
	DWORD sttime_;
	DWORD endtime_;
	channelMap _channels;
//	ThreadDecoding* _TDecoding;
	PacketQueue _Queue;
        
    DWORD user_id_;
    DWORD channel_id_;
    ctMutex mutex_audio_packet_;
    t_BufferCmdQueue queue_audio_packet_;

private:
	VoiceEngine* m_voe;
	VoEBase* base;
	VoECodec* codec;
	VoENetwork* netw;
	VoEMixer* mixer;
	VoERTP_RTCP* rtcp;
	VoEExternalMedia* media;
	VoEAudioProcessing* apm;

private:
    char path_[128];
    DWORD recid_;
};

#endif /* MIXERMISSION_H_ */

